using System;
using System.Reflection.Emit;
using Pine.Core;
using Pine.SourceParser.Tree;

namespace Pine.CodeGen
{
	public static class ConditionalStatementCodeGenerator
	{
		public static void GenerateBytecode(Context ctx, Statement stmt)
		{
			ConditionalStatement cond = (ConditionalStatement) stmt;
			LocalBuilder expr = ctx.il.DeclareLocal(typeof(Value));
			cond.e.GenerateBytecode(ctx, expr);
			
			Label elseLabel = ctx.il.DefineLabel();
			Label endLabel = ctx.il.DefineLabel();
			
			ctx.il.Emit(OpCodes.Ldloc, expr);
			ctx.il.Emit(OpCodes.Callvirt, typeof(Value).GetMethod("ToBoolean"));
			
			ctx.il.Emit(OpCodes.Brfalse, elseLabel);
			
			cond.ifstmt.GenerateBytecode(CodeUtilities.MakeChildScope(ctx));
			
			ctx.il.Emit(OpCodes.Br, endLabel);
			
			ctx.il.MarkLabel(elseLabel);
			
			if (cond.elsestmt != null)
				cond.elsestmt.GenerateBytecode(CodeUtilities.MakeChildScope(ctx));
			
			ctx.il.MarkLabel(endLabel);
		}
	}
}

